package com.alifi.crm.web.home.action;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import com.alibaba.buc.sso.client.util.SimpleUserUtil;
import com.alibaba.citrus.turbine.Context;
import com.alibaba.citrus.turbine.Navigator;
import com.alibaba.common.lang.StringUtil;
import com.alibaba.common.logging.Logger;
import com.alibaba.common.logging.LoggerFactory;
import com.alibaba.platform.buc.sso.common.dto.SimpleSSOUser;
import com.alifi.crm.biz.guess.Base;
import com.alifi.crm.biz.guess.EmployeeGuessManager;
import com.alifi.crm.biz.guess.GuessMessage;
import com.alifi.crm.biz.guess.GuessResult;
import com.alifi.crm.dal.object.EmployeeGuessDO;


/**
 * 
 * @author wenjing.huangwj
 *
 */
public class GuessAction {

	@Resource(name="employeeGuessManager")
	EmployeeGuessManager employeeGuessManager;
	
	protected static final Logger      logger = LoggerFactory.getLogger(GuessAction.class);
	
	/**
	 * ctx中会放入:   guessDO,  result, 出错时会放入: error 
	 * @param request
	 * @param response
	 * @param ctx
	 */
	public void doGuessAmount(HttpServletRequest request, HttpServletResponse response,Navigator nav,final Context ctx){
	
		try {
			ctx.put("action", "true");   //标记进入过action
			SimpleSSOUser user = SimpleUserUtil.findUser(request);
			if((user==null)||StringUtil.isBlank(user.getEmpId())){      //检查
				ctx.put("error", GuessMessage.NOT_GET_LOGIN_INFO);
				return;
			}
			ctx.put("user", user);
			EmployeeGuessDO guessDO = employeeGuessManager.getEmployeeGuess(StringUtil.trim(user.getEmpId()));
		    if(guessDO==null){
		    	ctx.put("error", GuessMessage.RIGHT_AMOUNT_IS_NULL);
		    	return;
		    }
		    ctx.put("guessDO", guessDO);
		    String guessAmount = StringUtil.trim(request.getParameter("guess_amount"));  //检查猜测额度
			if(StringUtil.isBlank(guessAmount)){        
				 ctx.put("error", GuessMessage.GUESS_AMOUNT_IS_NULL);
				 return;
			}
			Long guessAmountLong = null;
			try{
				guessAmountLong = Long.parseLong(guessAmount);
			}
			catch(Exception e){
				ctx.put("error", GuessMessage.GUESS_AMOUNT_MUST_BE_NUM);
				return;
			}
			if(Base.checkAndSetError(guessDO,ctx,employeeGuessManager)){
				return;
			}
			GuessResult guessResult = employeeGuessManager.guess(user.getEmpId(), guessAmountLong);
			EmployeeGuessDO currentGuessDO = employeeGuessManager.getEmployeeGuess(StringUtil.trim(guessDO.getEmployeeNum()));
			setGuessResultMessage(currentGuessDO,guessResult,ctx);
		    ctx.put("result", guessResult);
		    ctx.put("guessDO", currentGuessDO);
		} catch (Exception e) {
			ctx.put("error", new GuessMessage("exception",e.getMessage(),""));
			logger.error(e);
		} finally{
			printlnJsonDate(response,ctx);
		}
	}
	
	
	
	
	/**
	 * 设置猜测结果的文案
	 * @param guessDO
	 * @param guessResult
	 * @param ctx
	 */
	private void setGuessResultMessage(EmployeeGuessDO guessDO,GuessResult guessResult,final Context ctx){
		if(Base.isSmallerEndDate()){
			setGuessResultMessageContinue(guessDO,guessResult,ctx);
		}else{
			setGuessResultMessageEnd(guessDO,guessResult,ctx);
		}
	}
	
	/**
	 * 设置猜测结果的文案,不是最后一天
	 * @param guessDO
	 * @param guessResult
	 * @param ctx
	 */
	private void setGuessResultMessageContinue(EmployeeGuessDO guessDO,GuessResult guessResult,final Context ctx){
		
		if(GuessResult.相等.equals(guessResult)){
			ctx.put("error", GuessMessage.GUESS_RIGHT);
		}
		else if(GuessResult.相等没红包.equals(guessResult)){
			ctx.put("error", GuessMessage.GUESS_RIGHT_NO_ENVELOPE);
		}
		else if(GuessResult.相等随机没红包.equals(guessResult)){
			ctx.put("error", GuessMessage.GUESS_RIGHT_RANDOM_NO_ENVELOPE);
		}
		else if(GuessResult.大了.equals(guessResult)){
			if(guessDO.getLimitGuessTimes()<=guessDO.getGuessTimes()){   //大于等于上限次数
				if(Base.maxLimitTimes<=guessDO.getGuessTimes()){  //且大于3次
					ctx.put("error", GuessMessage.GUESS_BIG_OUT_LIMIT_TOMORROW_CONTINUE);
				}
				else{ //小于3次
					ctx.put("error", GuessMessage.GUESS_BIG_OUT_LIMIT_CONTINUE);
				}
			}
			else{ //小于上限次数
				ctx.put("error", GuessMessage.GUESS_BIG);
				ctx.put("continue_guess", true);
			}
		}
		else if(GuessResult.小了.equals(guessResult)){
			if(guessDO.getLimitGuessTimes()<=guessDO.getGuessTimes()){ //大于等于上限次数
				if(Base.maxLimitTimes<=guessDO.getGuessTimes()){  //且大于3次
					ctx.put("error", GuessMessage.GUESS_SMALL_OUT_LIMIT_TOMORROW_CONTINUE);
				}
				else{ //小于3次
					ctx.put("error", GuessMessage.GUESS_SMALL_OUT_LIMIT_CONTINUE);
				}
			}
			else{ //小于上限次数
				ctx.put("error", GuessMessage.GUESS_SMALL);
				ctx.put("continue_guess", true);
			}
		}
		else if(GuessResult.没拿到锁.equals(guessResult)){
			ctx.put("error", GuessMessage.NOT_GET_LOCK);
		}
		else{  //只有为GuessResult空才会进入这里
			logger.error("system error. return GuessResult is: "+guessResult+" in GuessAction.doGuessAmount");
			ctx.put("error", GuessMessage.SYSTEM_ERROR);
		}
	}
	
	
	/**
	 * 设置猜测结果的文案,是最后一天
	 * @param guessDO
	 * @param guessResult
	 * @param ctx
	 */
	private void setGuessResultMessageEnd(EmployeeGuessDO guessDO,GuessResult guessResult,final Context ctx){
		if(GuessResult.相等.equals(guessResult)){
			ctx.put("error", GuessMessage.GUESS_RIGHT);
		}
		else if(GuessResult.相等没红包.equals(guessResult)){
			ctx.put("error", GuessMessage.GUESS_RIGHT_NO_ENVELOPE_END);
		}
		else if(GuessResult.相等随机没红包.equals(guessResult)){
			ctx.put("error", GuessMessage.GUESS_RIGHT_RANDOM_NO_ENVELOPE_END);
		}
		else if(GuessResult.大了.equals(guessResult)){
			if(guessDO.getLimitGuessTimes()<=guessDO.getGuessTimes()){   //大于等于上限次数
				if(Base.maxLimitTimes<=guessDO.getGuessTimes()){  //且大于3次
					ctx.put("error", GuessMessage.GUESS_BIG_OUT_LIMIT_END);
				}
				else{ //小于3次
					ctx.put("error", GuessMessage.GUESS_BIG_OUT_LIMIT_CONTINUE);
				}
			}
			else{ //小于上限次数
				ctx.put("error", GuessMessage.GUESS_BIG);
				ctx.put("continue_guess", true);
			}
		}
		else if(GuessResult.小了.equals(guessResult)){
			if(guessDO.getLimitGuessTimes()<=guessDO.getGuessTimes()){ //大于等于上限次数
				if(Base.maxLimitTimes<=guessDO.getGuessTimes()){  //且大于3次
					ctx.put("error", GuessMessage.GUESS_SMALL_OUT_LIMIT_END);
				}
				else{ //小于3次
					ctx.put("error", GuessMessage.GUESS_SMALL_OUT_LIMIT_CONTINUE);
				}
			}
			else{ //小于上限次数
				ctx.put("error", GuessMessage.GUESS_SMALL);
				ctx.put("continue_guess", true);
			}
		}
		else if(GuessResult.没拿到锁.equals(guessResult)){
			ctx.put("error", GuessMessage.NOT_GET_LOCK);
		}
		else{  //只有为GuessResult空才会进入这里
			logger.error("system error. return GuessResult is: "+guessResult+" in GuessAction.doGuessAmount");
			ctx.put("error", GuessMessage.SYSTEM_ERROR);
		}
	}
	
	
	/**
	 * json中一定包含  message,code,pic
	 * @param response
	 * @param ctx
	 * @throws IOException
	 */
	private void printlnJsonDate(HttpServletResponse response,final Context ctx){
		JSONObject object = new JSONObject();
		object.put("result", ctx.get("result"));
		if(ctx.get("error")!=null){
			GuessMessage guessMessage = (GuessMessage)ctx.get("error");
			object.put("message", guessMessage.getMessage());
			object.put("code", guessMessage.getCode());
			object.put("pic", guessMessage.getPicture());
			if(ctx.get("continue_guess")!=null){
				object.put("continue_guess", "true");
			}
		}
		if(ctx.get("guessDO")!=null){
			EmployeeGuessDO currentGuessDO = (EmployeeGuessDO)ctx.get("guessDO");
			object.put("active_times", Base.toStringSubtract(currentGuessDO.getLimitGuessTimes(),currentGuessDO.getGuessTimes()));
		}
		try {
			response.getWriter().println(object.toString());
		} catch (IOException e) {
			logger.error(e);
		}
	}
	


}
